package com.yanxu.service;

import cn.hutool.core.bean.BeanUtil;
import com.yanxu.config.OAuth2ClientConfiguration;
import com.yanxu.constant.ApiConstant;
import com.yanxu.domain.OAuthDinerInfo;
import com.yanxu.model.domain.ResultInfo;
import com.yanxu.utils.AssertUtil;
import com.yanxu.utils.ResultInfoUtil;
import com.yanxu.vo.LoginDinerInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.LinkedHashMap;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025-09-25-2025
 * @Description: 食客服务业务逻辑层
 */
@Service
public class DinersService {

    @Resource
    private RestTemplate restTemplate;

    @Value("${service.name.ms-oauth-server}")
    private String oauthServerName;

    @Resource
    private OAuth2ClientConfiguration oAuth2ClientConfiguration;


    @SuppressWarnings("all")
    public ResultInfo signIn(String account, String password, String path) {
        // 参数校验
        AssertUtil.isNotEmpty(account, "请输入登录帐号");
        AssertUtil.isNotEmpty(password, "请输入登录密码");
        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);  //请求表单的形式
        // 构建请求体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("username", account);
        body.add("password", password);
        body.setAll(BeanUtil.beanToMap(oAuth2ClientConfiguration));
        // 请求头和请求体，一起构建一个 HttpEntity
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
        //设置 authorization
        restTemplate.getInterceptors().add(
                new BasicAuthenticationInterceptor(oAuth2ClientConfiguration.getClientId(), oAuth2ClientConfiguration.getSecret())
        );

        //发送请求
        ResponseEntity<ResultInfo> result =
                restTemplate.postForEntity(oauthServerName + "oauth/token", entity, ResultInfo.class);

        // 处理返回结果
        // 校验 http 请求的状态码（http请求是否成功）
        AssertUtil.isTrue(result.getStatusCode() != HttpStatus.OK, "登录失败");
        // 校验返回结果的状态码
        ResultInfo resultInfo = result.getBody();
        if(resultInfo.getCode() != ApiConstant.SUCCESS_CODE){
            // 登录失败
            resultInfo.setData(resultInfo.getMessage());
            return resultInfo;
        }
        // 这里的 Data 是一个 LinkedHashMap 转成了域对象 OAuthDinerInfo
        Object resultData = resultInfo.getData();
        OAuthDinerInfo dinerInfo = BeanUtil.fillBeanWithMap((LinkedHashMap) resultData,
                new OAuthDinerInfo(), false);
        // 根据业务需求返回视图对象
        LoginDinerInfo loginDinerInfo = new LoginDinerInfo();
        loginDinerInfo.setAvatarUrl(dinerInfo.getAvatarUrl());
        loginDinerInfo.setNickname(dinerInfo.getNickname());
        loginDinerInfo.setToken(dinerInfo.getAccessToken());
        return ResultInfoUtil.buildSuccess(path,loginDinerInfo);
    }
}